<template>
  <div class="login">
    <div class="login-container">
      <h1>管理员登录</h1>
      <form @submit.prevent="handleLogin">
        <div class="input-group">
          <label for="username">用户名：</label>
          <input v-model="username" type="text" id="username" required placeholder="请输入用户名" />
        </div>
        <div class="input-group">
          <label for="password">密码：</label>
          <input v-model="password" type="password" id="password" required placeholder="请输入密码" />
        </div>
        <button type="submit" class="login-button">登录</button>
      </form>
      <p v-if="error" class="error">{{ error }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: '',
      error: null,
    };
  },
  methods: {
    async handleLogin() {
      try {
        this.error = null;

        const response = await axios.post(axios.defaults.baseURL+'/api/auth/loginOrRegister', {
          phoneNumber: this.username,
          password: this.password,
          role: 'ADMIN',
        });

        const { token, user } = response.data;

        // 调用 Vuex 的 login 方法
        this.$store.dispatch('login', { token, adminInfo: { ...user, role: user.role } });

        // 将 token 存储到 sessionStorage
        sessionStorage.setItem('token', token);

        // 跳转到后台管理页
        this.$router.push('/admin/dashboard');
      } catch (err) {
        console.error('Login Error:', err);
        this.error = err.response?.data || '登录失败，请重试';  // 处理后端返回的错误
      }
    },
  },
};
</script>



<style scoped>
/* 页面背景渐变 */
.login {
  background: linear-gradient(135deg, #dfe9f3 10%, white);
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  background: #fff;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 450px;
  width: 100%;
}

.login-container h1 {
  font-size: 32px;
  color: #333;
  margin-bottom: 40px;
  font-weight: 700;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

.input-group {
  margin-bottom: 20px;
  text-align: left;
}

.input-group label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  display: block;
  font-weight: 500;
}

.input-group input {
  width: 100%;
  padding: 14px;
  border-radius: 8px;
  border: 1px solid #ccc;
  font-size: 16px;
  transition: all 0.3s ease;
  box-sizing: border-box;
  background-color: #f9f9f9;
}

.input-group input:focus {
  border-color: #007bff;
  background-color: #ffffff;
  outline: none;
}

.login-button {
  padding: 14px;
  width: 100%;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.login-button:hover {
  background-color: #0056b3;
}

.error {
  color: red;
  font-size: 14px;
  margin-top: 15px;
}
</style>
